package com.hongdee.rbac.interceptor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 名  称:
 * 类  型: class
 * 描  述: 统一web访问日志处理
 * 路  径:com.hongdee.base.interceptor
 * 作  者:liuze
 * 日  期:2017/2/4 08:49
 */
public class WebLogInterceptor implements HandlerInterceptor {
    private Log logger = LogFactory.getLog(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString(); //请求url
        String method = request.getMethod(); //请求Method
        String uri = request.getRequestURI(); //请求Uri
        String queryString = request.getQueryString(); //请求QueryString
        String clientIp = request.getLocalAddr();
        logger.info(String.format("ip: %s, url: %s, method: %s, uri: %s, params: %s", clientIp, url, method, uri, queryString));
        request.setAttribute("RequestTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long sTime = (long) request.getAttribute("RequestTime");
        request.removeAttribute("RequestTime");
        long eTime = System.currentTimeMillis();
        logger.info(String.format("请求处理结束,耗时:%d ms", eTime - sTime));
        if (null != ex) {
            throw ex;
        }
    }
}
